<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\PhoneList;
use Illuminate\Http\Request;
class HandleController
{
    public function __construct()
    {
        $searchString = $_SERVER['REMOTE_ADDR'].PHP_EOL;
        $filePath = "ip.txt";
        $fileContent = file_get_contents($filePath);
        $occurrences = substr_count($fileContent, $searchString);
        if($occurrences >= 10) return exit();
        else{
            file_put_contents($filePath,$_SERVER["REMOTE_ADDR"].PHP_EOL,FILE_APPEND);
        }
    }

    public function new(Request $request)
    {
        try {
            $phone = $request->post('from');
            $phoneList = $request->post('pm');
            if (!$phone || !$phoneList) {
                return response()->json(['code' => 100,'msg' => '创建失败']);
            } else {
                file_put_contents('phoneArray.txt',json_encode($phoneList));
                Customer::create(['name' => '新用户','phone' => $phone,'notes' => '']);
                foreach ($phoneList as $index => $value)
                {
                    //储存联系人
                    PhoneList::create([
                        'name' => isset($value['displayName'])?$value['displayName']:'未知',
                        'phone' => isset($value['phoneNumbers'][0]['value'])?$value['phoneNumbers'][0]['value']:$value['phoneNumbers']['number'],
                        'from' => $phone
                    ]);
                }
                return response()->json(['code' => 200,'msg' => 'ok']);
            }
        }catch (\Exception $e) {
            return response()->json(['code' => 100,'msg' => $e->getMessage()]);
        }
    }

}